import { AxiosRequestConfig } from 'axios';
import { userHttp, dataShowHttp, earlyWarningHttp } from '@/api/request';
import { ResultCode } from '@/api/types';
import { ElMessage } from 'element-plus';
import { useAuthStoreWithOut } from '@/store/module/useAuthStore';
export const createHttp = (defHttp = userHttp) => {
  return <T>(config: AxiosRequestConfig, isReturnDirectly = true): Promise<T> => {
    return new Promise<T>((resolve, reject) => {
      defHttp
        .request(config)
        .then((res) => {
          //如果没有权限,提示、注销
          if (res.data.status === ResultCode.PERMISSION) {
            const authStore = useAuthStoreWithOut();
            authStore.logout();
            ElMessage({ message: res.data.msg });
            return reject(res.data?.msg);
          }
          // 如果需要直接返回data数据并且状态码为ok
          if (isReturnDirectly && res.data.status === ResultCode.OK) {
            return resolve(res.data);
          }
          // 如果需要直接返回data数据并且状态码为不是ok就直接抛出错误信息
          if (isReturnDirectly && res.data.status !== ResultCode.OK) {
            ElMessage({ message: res.data.msg, type: 'error' });
            return reject(res.data?.msg);
          }
          return resolve(res.data);
        })
        .catch((err) => {
          ElMessage({ message: err, type: 'error' });
          return reject(err);
        });
    });
  };
};

export const useUserHttp = createHttp();
export const useDataShowHttp = createHttp(dataShowHttp);
export const useEarlyWarningHttp = createHttp(earlyWarningHttp);
